import 'dart:convert';
import 'dart:developer' as developer;

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';

class WolaiApi extends StatelessWidget {
  final String _data;

  const WolaiApi({super.key, required String data}) : _data = data;

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
        future: insertData(),
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.hasData != false &&
              snapshot.connectionState == ConnectionState.done) {
            developer.log('响应结果：${snapshot.data}');
            return SelectableText(snapshot.data);
          } else {
            developer.log('等待响应结果中');
            return const SelectableText("等待响应结果中");
          }
        });
  }

  Future<String?> getToken() async {
    final dio = Dio();
    Response<String> response =
        await dio.post("https://openapi.wolai.com/v1/token", data: {
      "appId": "kxBwUkcnZ5x9SNxpfGKRam",
      "appSecret":
          "cbe263c707dd29b8ab660a6ef94da0f80f40cf7573a45fd05c40d60d04c262de"
    });
    Map<String, dynamic> dataJson = jsonDecode(response.data ?? "");
    return dataJson["data"]["app_token"];
  }

  Future<String?> insertData() async {
    String? id = RegExp("\nid:(.*)").firstMatch(_data)?.group(1).toString();
    print("id$id");
    String? contentStr =
        RegExp("\ndata:([\\s\\S]*)").firstMatch(_data)?.group(1).toString();
    List content = jsonDecode(contentStr!);
    //wolai要求一次将 content 拆分成小于 20 的多个子 content
    List<List<dynamic>> subContent = [];
    for (int i = 0; i < content.length; i += 10) {
      int endIndex = i + 10;
      if (endIndex > content.length) {
        endIndex = content.length;
      }
      subContent.add(content.sublist(i, endIndex));
    }
    final dio = Dio();
    dio.options.headers.addAll({"Authorization": await getToken()});
    for (var i in subContent) {
      dio.post("https://openapi.wolai.com/v1/databases/$id/rows",
          data: {"rows": i});
    }
    return "成功";
  }
}
